/**
* Copyright (C) 2018-2020
* All rights reserved, Designed By www.yixiang.co
* 注意：
* 本软件为www.yixiang.co开发研制，未经购买不得使用
* 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
* 一经发现盗用、分享等行为，将追究法律责任，后果自负
*/
package co.yixiang.modules.auction.rest;

import co.yixiang.dozer.service.IGenerator;
import co.yixiang.enums.BillDetailEnum;
import co.yixiang.enums.BillEnum;
import co.yixiang.logging.aop.log.Log;
import co.yixiang.modules.auction.domain.AuctionOrder;
import co.yixiang.modules.auction.domain.YxAuctionTakeDelivery;
import co.yixiang.modules.auction.service.AuctionOrderService;
import co.yixiang.modules.auction.service.YxAuctionTakeDeliveryService;
import co.yixiang.modules.auction.service.dto.YxAuctionTakeDeliveryDto;
import co.yixiang.modules.auction.service.dto.YxAuctionTakeDeliveryQueryCriteria;
import co.yixiang.modules.user.domain.YxUser;
import co.yixiang.modules.user.domain.YxUserBill;
import co.yixiang.modules.user.service.YxUserBillService;
import co.yixiang.modules.user.service.YxUserService;
import co.yixiang.utils.RedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;

/**
* @author hupeng
* @date 2021-05-19
*/
@AllArgsConstructor
@Api(tags = "拍品提货管理")
@RestController
@RequestMapping("/api/yxAuctionTakeDelivery")
public class YxAuctionTakeDeliveryController {

    private final YxAuctionTakeDeliveryService yxAuctionTakeDeliveryService;
    private final AuctionOrderService auctionOrderService;
    private final IGenerator generator;
    private final RedisUtils redisUtils;
    private final YxUserBillService userBillService;
    private final YxUserService userService;


    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    public void download(HttpServletResponse response, YxAuctionTakeDeliveryQueryCriteria criteria) throws IOException {
        yxAuctionTakeDeliveryService.download(generator.convert(yxAuctionTakeDeliveryService.queryAll(criteria), YxAuctionTakeDeliveryDto.class), response);
    }

    @GetMapping
    @Log("查询拍品提货")
    @ApiOperation("查询拍品提货")
    public ResponseEntity<Object> getYxAuctionTakeDeliverys(YxAuctionTakeDeliveryQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(yxAuctionTakeDeliveryService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增拍品提货")
    @ApiOperation("新增拍品提货")
    @PreAuthorize("@el.check('admin','yxAuctionTakeDelivery:add')")
    public ResponseEntity<Object> create(@Validated @RequestBody YxAuctionTakeDelivery resources){
        return new ResponseEntity<>(yxAuctionTakeDeliveryService.save(resources),HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改拍品提货")
    @ApiOperation("修改拍品提货")
    @PreAuthorize("@el.check('admin','yxAuctionTakeDelivery:edit')")
    public ResponseEntity<Object> update(@Validated @RequestBody YxAuctionTakeDelivery resources){
        yxAuctionTakeDeliveryService.updateById(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @GetMapping("/editStatus")
    @Log("修改状态")
    @ApiOperation("修改状态")
    public ResponseEntity<Object> editStatus(@RequestParam(value = "id" , required = false) Long id ,
                                             @RequestParam(value = "status" ,required = false) Integer status){
        YxAuctionTakeDelivery auctionTakeDelivery = yxAuctionTakeDeliveryService.getById(id);
        auctionTakeDelivery.setStatus(status);
        yxAuctionTakeDeliveryService.updateById(auctionTakeDelivery);
        AuctionOrder auctionOrder = auctionOrderService.getById(auctionTakeDelivery.getOid());
        //赠送积分
        if (status == 3){
            String ratio = String.valueOf(redisUtils.get("dict:sendRatio"));
            YxUser user = userService.getById(auctionOrder.getUserId());
            BigDecimal i = new BigDecimal(ratio).multiply(auctionTakeDelivery.getTotalPrice());
            BigDecimal add = user.getIntegral().add(i);
            user.setIntegral(add);
            userService.updateById(user);

            //增加记录
            YxUserBill integralBill = YxUserBill.builder()
                    .uid(user.getUid())
                    .title("反赠银锭")
                    .linkId(auctionTakeDelivery.getId().toString())
                    .type(BillDetailEnum.TYPE_1.getValue())
                    .category(BillDetailEnum.CATEGORY_2.getValue())
                    .number(i)
                    .balance(add)
                    .mark("反赠银锭")
                    .status(BillEnum.STATUS_1.getValue())
                    .pm(BillEnum.PM_1.getValue())
                    .build();
            userBillService.save(integralBill);
        }

        return new ResponseEntity<>(HttpStatus.OK);
    }

    @Log("删除拍品提货")
    @ApiOperation("删除拍品提货")
    @PreAuthorize("@el.check('admin','yxAuctionTakeDelivery:del')")
    @DeleteMapping
    public ResponseEntity<Object> deleteAll(@RequestBody Long[] ids) {
        Arrays.asList(ids).forEach(id->{
            yxAuctionTakeDeliveryService.removeById(id);
        });
        return new ResponseEntity<>(HttpStatus.OK);
    }
}
